package com.beimihu.leetcode;

public class reverseWords {
    public static String  reverseWords(String s) {
        String[] words = s.trim().split("\\s+");  // 去除首尾空格并按一个或多个空格分割字符串
        StringBuilder result = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--) {
            if (!words[i].isEmpty()) {  // 只处理非空字符串
                result.append(words[i]);
                if (i > 0) {  // 如果不是最后一个单词，添加空格
                    result.append(" ");
                }
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String s = "hello world, god bless you";
        String reverse = reverseWords(s);
        System.out.println(reverse);
    }
}
